package com.gm.commonlib.util.permission.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.gm.commonlib.util.permission.PermissionManager;
import com.gm.commonlib.util.permission.annotations.PermissionDenied;
import com.gm.commonlib.util.permission.annotations.PermissionGranted;
import com.gm.commonlib.util.permission.annotations.PermissionStatistics;
import com.gm.commonlib.util.permission.core.PermissionHelper;
import com.gm.commonlib.util.permission.domain.PermissionObject;
import com.gm.commonlib.util.permission.interfaces.IPermissionCallback;
import com.gm.commonlib.util.permission.utils.Utils;
import com.youth.banner.util.LogUtils;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class PermissionActivity extends Activity {
    //权限请求码
    private static final int PERMISSION_REQUEST_CODE = 0;

    private PermissionObject permissionObject;
    public static PermissionActivity activity;

    public static void apply(Context context, PermissionObject permissionObject, IPermissionCallback resultListener) {
        if (permissionObject == null
                || TextUtils.isEmpty(permissionObject.getRequestId())) {

            showMessage(context, "申请动态权限，缺少参数！");
            if (resultListener != null) {
                resultListener.statisticsPermission(new HashSet<String>(), new HashSet<String>());
                resultListener.onPermissionResult(false, new HashSet<String>());
            }
            return;
        }

        if (isNullOrEmpty(permissionObject.getPermissions())) {

            if (resultListener != null) {
                resultListener.statisticsPermission(new HashSet<String>(), new HashSet<String>());
                resultListener.onPermissionResult(true, new HashSet<String>());
            }
            return;
        }

        //todo 先检查是否所有权限已经通过了，通过了直接返回成功
        if (Utils.isOverMarshmallow()) {

            if (resultListener != null && resultListener.preCheckPermission(context, permissionObject.getPermissions())) {
                HashSet<String> passPermission = new HashSet<>(Arrays.asList(permissionObject.getPermissions()));
                resultListener.statisticsPermission(new HashSet<String>(), passPermission);
                resultListener.onPermissionResult(true, passPermission);
                return;
            }

            PermissionManager.instance.setCallback(permissionObject.getRequestId(), resultListener);
            context.startActivity(new Intent(context, PermissionActivity.class)
                    .putExtra("PermissionObject", permissionObject)
                    .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION));
        } else {
            if (resultListener != null) {
                HashSet<String> deniSet = new HashSet<>();
                HashSet<String> passSet = new HashSet<>();

                if (context instanceof Activity) {
                    Utils.findDeniedPermissions((Activity) context, deniSet, passSet, permissionObject.getPermissions());
                }

                resultListener.statisticsPermission(deniSet, passSet);
                if (deniSet.isEmpty()) {
                    resultListener.onPermissionResult(true, passSet);
                } else {
                    resultListener.onPermissionResult(false, deniSet);
                }
            }
        }
    }

    private static void showMessage(Context context, String message) {
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    }

    private static <T> boolean isNullOrEmpty(T[] values) {
        return values == null || values.length == 0;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity=this;
        Window window = getWindow();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // Android 5.0 以上 全透明
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            // 状态栏（以上几行代码必须，参考setStatusBarColor|setNavigationBarColor方法源码）
            window.setStatusBarColor(Color.TRANSPARENT);
            // 虚拟导航键
            window.setNavigationBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // Android 4.4 以上 半透明
            // 状态栏
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            // 虚拟导航键
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }

        doRequest();
    }

    private void doRequest() {
        permissionObject = (PermissionObject) getIntent().getSerializableExtra("PermissionObject");
        if (permissionObject == null) {
            showMessage(this, "申请动态权限，缺少参数！");
            callFinish();
            return;
        }

        if (TextUtils.isEmpty(permissionObject.getRequestId())) {
            showMessage(this, "申请动态权限，缺少参数！");
            callFinish();
            return;
        }
        if (isNullOrEmpty(permissionObject.getPermissions())) {
            PermissionManager.instance.removeCallback(permissionObject.getRequestId());
            showMessage(this, "申请动态权限，缺少参数！");
            callFinish();
            return;
        }

        PermissionHelper.with(this).addRequestCode(PERMISSION_REQUEST_CODE).permissions(permissionObject.getPermissions()).request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionHelper.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @PermissionGranted(requestCode = PERMISSION_REQUEST_CODE)
    private void permissionAllow(Set<String> deniedPermissions) {
        IPermissionCallback resultListener = PermissionManager.instance.getCallback(permissionObject.getRequestId());
        PermissionManager.instance.removeCallback(permissionObject.getRequestId());
        if (resultListener != null) {
            resultListener.onPermissionResult(true, deniedPermissions);
        }
        setResult(RESULT_OK);
        callFinish();
    }

    @PermissionDenied(requestCode = PERMISSION_REQUEST_CODE)
    private void permissionFile(Set<String> passPermission) {
        if (!TextUtils.isEmpty(permissionObject.getFailureResponse())) {
            showMessage(this, permissionObject.getFailureResponse());
        }

        IPermissionCallback resultListener = PermissionManager.instance.getCallback(permissionObject.getRequestId());
        PermissionManager.instance.removeCallback(permissionObject.getRequestId());
        if (resultListener != null) {
            resultListener.onPermissionResult(false, passPermission);
        }
        setResult(RESULT_CANCELED);
        callFinish();
    }

    @PermissionStatistics(requestCode = PERMISSION_REQUEST_CODE)
    public void statisticsPermission(Set<String> deniedPermissions, Set<String> passPermission) {
        IPermissionCallback resultListener = PermissionManager.instance.getCallback(permissionObject.getRequestId());
        resultListener.statisticsPermission(deniedPermissions, passPermission);
    }

    public void callFinish() {
        finish();
        overridePendingTransition(0, 0);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtils.d("pe onDestroy");
        activity=null;
    }

}
